package com.wxy.demo.advice;

import com.wxy.demo.core.ApiResponse;
import com.wxy.demo.core.BizException;
import com.wxy.demo.core.ErrorId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    public ApiResponse<Object> Exception(Exception e) {
        ErrorId errorId = ErrorId.get();
        log.error("操作失败：{}", errorId.getErrorId(), e);
        return ApiResponse.fail("操作失败", errorId);
    }

    @ExceptionHandler(value = BizException.class)
    public ApiResponse<Object> BizException(BizException e) {
        return ApiResponse.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                FieldError fieldError = (FieldError) errors.get(0);
                return ApiResponse.fail(fieldError.getDefaultMessage());
            }
        }
        return ApiResponse.fail("参数验证失败");
    }
}
